<?php

namespace App\Http\Controllers;

use App\Services\DBAPP;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
 * url的形式为:
 * put      api/data/table      新增数据
 * post     api/data/table/id   修改数据
 * delete   api/data/table/id   删除数据
 * get      api/data/table      获取列表
 * get      api/data/table/id   获取单条
 *
 * Class DataController
 * @package App\Http\Controllers
 */
class DataController extends Controller
{
    /**
     * 批量获取
     * @param Request $i
     * @param $db
     * @param $table
     * @return JsonResponse
     */
    public function index(Request $i, $db, $table) : JsonResponse {
        $search = $i->input('search', '[]');
        $search = json_decode($search, true);
        $db =  DBAPP::db()->table($table)->select("*");
        foreach($search as $item) {
            $key = $item['key'];
            $val = $item['val'];
            $relation = $item['relation'];
            switch ($relation) {
                case '=': ;
                case '<': ;
                case '>': ;
                case '<=':;
                case '>=':;
                case '<>': $db->where($key, $relation, $val);break;
                default: break;
            }
        }
        $data = $db->paginate(20);
        return self::json(200, 'ok', $data);
    }

    /**
     * 单条查询
     * @param Request $i
     * @param $table
     * @param $id
     * @return JsonResponse
     */
    public function detail(Request $i, $db, $table, $id) : JsonResponse {
        $data = DBAPP::db()->table($table)->where('id', $id)->first();
        return self::json(200, 'ok', $data);
    }

    /**
     * 创建
     * @param Request $i
     * @param $table
     */
    public function create(Request $i, $db, $table) {
        $data = $i->input('data');
        $data['created_at'] = Carbon::now();
        $data['updated_at'] = Carbon::now();
        $id = DBAPP::db()->table($table)->insertGetId($data);
        $data = DBAPP::db()->table($table)->where('id', $id)->first();
        return self::json(200, 'success', $data);
    }

    /**
     * 更新
     * @param Request $i
     * @param $table
     */
    public function update(Request $i, $db, $table, $id) {
        $data = $i->input('data');
        $data['updated_at'] = Carbon::now();
        DBAPP::db()->table($table)->where('id', $id)->update($data);
        return self::json();
    }

    /**
     * 删除
     * @param Request $i
     * @param $table
     * @return Response
     */
    public function delete(Request $i, $database, $table, $id)  {

        DBAPP::db()->table($table)->where('id', $id)->delete();
        return self::json(200, 'ok');
    }
}
